<script setup lang="ts">
// 使用unplugin-vue-components默认会自动引入src/components目录下的sfc
// import CpNavBar from '@/components/CpNavBar.vue'
import { ref } from 'vue'
import { codeRules, mobileRules, passwordRules } from '@/utils/rules'
import { Toast, type FormInstance } from 'vant'
import { loginService, getCodeService, loginByCodeService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import qqImg from '@/assets/qq.svg'

const userStore = useUserStore()
const onClickRight = () => {
  router.push('/register')
}
const agree = ref(false) // 是否同意用户协议
const showPassword = ref(false) // 密码是否显示
const isPass = ref(true) // 是否密码登录
const loginData = ref({
  // mobile: import.meta.env.DEV ? '13230000001' : '',
  mobile: '13230000001',
  password: import.meta.env.DEV ? 'abc12345' : '',
  code: '',
})
// 点击登录
const router = useRouter()
// 获取路由参数
const fromUrl = router.currentRoute.value.query.fromUrl as string
const login = async () => {
  if (!agree.value) {
    return Toast.fail('请勾选用户协议')
  }
  try {
    const res = await (isPass.value
      ? loginService({
          mobile: loginData.value.mobile,
          password: loginData.value.password,
        })
      : loginByCodeService({
          mobile: loginData.value.mobile,
          code: loginData.value.code,
        }))
    userStore.setUser(res) // 登录成功后,将用户信息存储到store中
    // 登录成功后,判断是否有fromUrl参数，有就跳转到fromUrl，没有就跳转到/user个人中心
    router.replace(fromUrl || '/user')
    Toast.success('登录成功')
  } catch (error) {
    console.log(error)
  }
}

// 表单实例
const formRef = ref<FormInstance>()
// 发送验证码
const countdown = ref(0) // 倒计时时间
let timer: any = null // 存储定时器id
const getCode = async () => {
  try {
    await formRef.value?.validate(['mobile'])
    Toast.success('发送验证码成功')
  } catch (error) {
    return Toast.fail('请输入正确的手机号')
  }
  try {
    const { code } = await getCodeService(loginData.value.mobile, 'login')
    loginData.value.code = code
    countdown.value = 60 // 设置倒计时时间
    // 开启定时器
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value === 0) clearInterval(timer)
    }, 1000)
  } catch (error) {}
}
</script>

<template>
  <cp-nav-bar title="登录" right-text="注册" @click-right="onClickRight" />
  <div class="login">
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录  ' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ isPass ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- == form 表单 == -->
    <van-form autocomplete="off" @submit="login" ref="formRef">
      <van-field
        placeholder="请输入手机号"
        type="tel"
        v-model="loginData.mobile"
        :rules="mobileRules"
        name="mobile"
      ></van-field>

      <van-field
        v-if="isPass"
        :placeholder="'请输入密码'"
        :type="showPassword ? 'text' : 'password'"
        v-model="loginData.password"
        :rules="passwordRules"
      >
        <template #button>
          <cp-icon
            v-if="isPass"
            :name="showPassword ? 'login-eye-on' : 'login-eye-off'"
            @click="showPassword = !showPassword"
          ></cp-icon>
        </template>
      </van-field>
      <van-field
        v-else
        :placeholder="'请输入验证码'"
        type="text"
        v-model="loginData.code"
        :rules="codeRules"
      >
        <template #button>
          <span class="get-code" @click="getCode" v-if="countdown === 0">获取验证码</span>
          <span class="sended-code" v-else>{{ countdown }}秒后重新获取</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <router-link to="/login/protocol">用户协议</router-link>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">登 录</van-button>
      </div>
      <div class="cp-cell" @click="Toast('暂未实现此功能')">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 第三方登录（qq登录） -->
    <van-divider class="login-divider">第三方登录</van-divider>
    <div class="qq-login" @click="Toast('暂未实现此功能')">
      <van-image width="44" :src="qqImg"></van-image>
    </div>

    <!-- 说明 -->
    <van-divider>
      为了方便测试，您可以使用手机号：13230000001~100 密码：abc12345 登录
      <br />
      支付沙箱账号：qowego7611@sandbox.com，密码： 全为1
      <br />
      医生端地址：https://consult-doc-client.itheima.net/
    </van-divider>
  </div>
</template>

<style lang="scss" scoped>
.login {
  padding-top: 46px;
  &-head {
    padding: 30px 30px 50px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: bold;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  .van-form {
    padding: 0 14px;
    .cp-cell {
      height: 52px;
      padding: 14px 16px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      .van-checkbox {
        a {
          color: var(--cp-primary);
          padding: 0 5px;
        }
      }
    }
    .get-code {
      color: var(--cp-primary);
    }
    .sended-code {
      color: var(--cp-price);
    }
  }
  .login-divider {
    margin-top: 50px;
  }
  .qq-login {
    text-align: center;
  }
}
</style>
